/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb138.videodes.api.base;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author pseudo
 * 
 * This class provide a safe completion of xquery statements 
 * Class isn't finished yet
 */
public class XPreparedStatement {  
    private String query;
    private Map<Integer, Object> params = new HashMap<Integer, Object>();
    
    /**
     * Constructor of class
     * @param query xquery with "?" instead of parameters 
     */
    public XPreparedStatement(String query){
	this.query = query;
    }
    
    /**
     * 
     * @param index position of representing "?" character 
     * @param val value
     */
    public void setInt(int index, Integer val){
	params.put(index, Integer.valueOf(val));
    }
    
    /**
     * 
     * @param index
     * @param val 
     */
    public void setLong(int index, Long val){
	params.put(index, Long.valueOf(val));
    }
    
    /**
     * 
     * @param index
     * @param val 
     */
    public void setString(int index, String val){
	params.put(index, val);
    }
    
    /**
     * 
     * @param index
     * @param val 
     */
    public void setDouble(int index, Double val){
	params.put(index, Double.valueOf(val));
    }
    
    /**
     * Replace "?" characters with their values
     * @return 
     */
    private String setParams(){
	StringBuilder q = new StringBuilder(query);
	int i = 1;
	int index = query.indexOf('?');
	while (index != -1){
	    Object param = params.get(i);
	    if (param != null){
		q.replace(index, index + 1, param.toString());
	    }
	    index = query.indexOf('?', index + 1);
	    i++;
	}	
	return q.toString();
    }
    
    @Override
    public String toString(){
	return setParams();
    }    
}
